package com.xpmusic.controller.consumer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet("/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String musicName = request.getParameter("musicName");
        //musicName = new String(musicName.getBytes(),"UTF-8");
        String path = this.getServletContext().getRealPath("/music/");
        System.out.println("musicName:" + musicName);
        System.out.println("path:" + path);
        File file = new File(path + musicName);
        if(!file.exists()){
            request.setAttribute("message","资源文件不存在!");
            request.getRequestDispatcher("personalMusic.jsp").forward(request, response);
            return;
        }
        //处理文件名
        String realName = new String(musicName.split("-")[1].replace(" ","").getBytes("UTF-8"), "ISO-8859-1");;
        //设置响应头，控制浏览器下载该文件URLEncoder.encode(realName,"UTF-8")
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + realName);
        //读取要下载的文件，保存到输出流
        FileInputStream inputStream = new FileInputStream(path + musicName);
        System.out.println("实际下载地址：" + path + musicName);
        //创建输出流
        OutputStream outputStream = response.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区
        while((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        //关闭流
        outputStream.close();
        inputStream.close();
    }
}
